package com.liuche.pictureserver.controller.user;

import com.liuche.pictureserver.common.exception.ErrorCode;
import com.liuche.pictureserver.common.exception.ThrowUtils;
import com.liuche.pictureserver.common.resp.BaseResponse;
import com.liuche.pictureserver.common.resp.ResUtils;
import com.liuche.pictureserver.pojo.req.user.UserLoginReqVO;
import com.liuche.pictureserver.pojo.req.user.UserRegistryReqVO;
import com.liuche.pictureserver.pojo.resp.user.UserInfoRespVO;
import com.liuche.pictureserver.service.IUserService;
import com.liuche.pictureserver.utils.BeanUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 用户模块
 *
 * @author liuche
 */
@Tag(name = "user")
@RestController
@RequestMapping("/v1/user")
public class UserController {
    @Resource
    private IUserService userService;

    /**
     * 用户注册
     *
     * @param req 注册请求
     * @return 结果
     */
    @Operation(summary = "用户注册")
    @PostMapping("/registry")
    public BaseResponse<Long> registry(@RequestBody @Validated UserRegistryReqVO req) {
        return ResUtils.success(userService.registry(req));
    }


    /**
     * 用户登录
     *
     * @param req     登录请求
     * @param request 请求头信息
     * @return 结果
     */
    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public BaseResponse<UserInfoRespVO> login(@RequestBody @Validated UserLoginReqVO req, HttpServletRequest request) {
        ThrowUtils.throwIf(ObjectUtils.isEmpty(request), ErrorCode.PARAMS_ERROR);
        return userService.login(req, request);
    }

    /**
     * 获取当前登录用户信息
     *
     * @param request 请求信息
     * @return 结果
     */
    @Operation(summary = "得到当前登录用户")
    @GetMapping("/curUser")
    public BaseResponse<UserInfoRespVO> getLoginUser(HttpServletRequest request) {
        ThrowUtils.throwIf(ObjectUtils.isEmpty(request), ErrorCode.PARAMS_ERROR);
        return ResUtils.success(BeanUtil.toBean(userService.getCurUser(request), UserInfoRespVO.class));
    }

    /**
     * 退出登录
     *
     * @param request 请求信息
     * @return 结果
     */
    @Operation(summary = "退出登录")
    @GetMapping("/logout")
    public BaseResponse<Boolean> logout(HttpServletRequest request) {
        ThrowUtils.throwIf(ObjectUtils.isEmpty(request), ErrorCode.PARAMS_ERROR);
        return ResUtils.success(userService.logout(request));
    }

}
